package com.qiantu.api.db;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.qiantu.api.db.database.LocalDataBase;
import com.qiantu.api.entity.ControllerBean;
import com.qiantu.api.db.greendao.ControllerBeanDao;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.SceneBean;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by cjc on 2019/5/7
 */
public class LLControllerDBManager {

    private final String TAG = "LLControllerDBManager";
    private volatile static LLControllerDBManager instance = null;
    private final static Object object = new Object();
    private final ControllerBeanDao mControllerBeanDao;
    private Context context;

    private LLControllerDBManager(Context context) {
        this.context = context;
        mControllerBeanDao = LocalDataBase.getInstance().getDaoSession(context).getControllerBeanDao();
    }

    public static LLControllerDBManager getInstance(Context context) {
        if (instance == null) {
            synchronized (object) {
                if (instance == null) {
                    instance = new LLControllerDBManager(context.getApplicationContext());
                }
            }
        }
        return instance;
    }

    public void clearFromDB() {
        mControllerBeanDao.deleteAll();
    }

    /**
     * 从服务器更新设备数据
     *
     * @param controllerList
     */
    public void refreshAllControllersTx(List<ControllerBean> controllerList) {
        LocalDataBase.getInstance().getDaoSession(context).runInTx(() -> {
            clearFromDB();
            if(controllerList == null){
                return;
            }
            Log.i("lzxzx", "refreshAllControllersTx:" + controllerList.size());
            for (ControllerBean controller : controllerList) {
                mControllerBeanDao.save(controller);
            }
        });
    }

    public void putInTx(List<ControllerBean> controllerList, HandleListener listener) {
        LocalDataBase.getInstance().getDaoSession(context).runInTx(() -> {
            for (ControllerBean controller : controllerList) {
                put(controller);
            }
            listener.onCompleted();
        });
    }

    public void refreshControllersByMaster(String masterSerialNo, List<ControllerBean> controllerList) {
        LocalDataBase.getInstance().getDaoSession(context).runInTx(() -> {
            List<ControllerBean> old =  mControllerBeanDao.queryBuilder()
                    .where(ControllerBeanDao.Properties.IsSlave.eq(true), ControllerBeanDao.Properties.MasterSerialNo.eq(masterSerialNo))
                    .list();
            mControllerBeanDao.deleteInTx(old);
            for (ControllerBean controller : controllerList) {
                mControllerBeanDao.save(controller);
                LLDeviceDBManager.getInstance(context).updateDeviceByControllerSerialNo(controller.getControllerSerialNo(), controller.getDeviceItems());
            }
        });
    }

    /**
     * 保存或者更新设备
     *
     * @param controller
     */
    public void put(ControllerBean controller) {
        if (controller == null)
            return;
        String serialNo = controller.getControllerSerialNo();
        if (serialNo != null && !TextUtils.isEmpty(serialNo)) {
            ControllerBean oldController = mControllerBeanDao.queryBuilder()
                    .where(ControllerBeanDao.Properties.ControllerSerialNo.eq(serialNo))
                    .unique();
            if (oldController != null) {
                controller.setLocalId(oldController.getLocalId());
            }
        }
        mControllerBeanDao.save(controller);
    }

    /**
     * 更新控制器名称
     *
     * @param serialNo
     * @param name
     */
    public void updateName(String serialNo, String name) {
        if (!TextUtils.isEmpty(serialNo)) {
            ControllerBean oldController = mControllerBeanDao.queryBuilder()
                    .where(ControllerBeanDao.Properties.ControllerSerialNo.eq(serialNo))
                    .unique();
            if (oldController != null) {
                oldController.setName(name);
                mControllerBeanDao.save(oldController);
            }
        }
    }

    /**
     * 更新控制器状态
     *
     * @param serialNo
     * @param stateType
     */
    public void updateStateType(String serialNo, int stateType) {
        if (!TextUtils.isEmpty(serialNo)) {
            ControllerBean oldController = mControllerBeanDao.queryBuilder()
                    .where(ControllerBeanDao.Properties.ControllerSerialNo.eq(serialNo))
                    .unique();
            if (oldController != null) {
                oldController.setStateType(stateType);
                mControllerBeanDao.save(oldController);
            }
        }
    }


    /**
     * 更新控制器停启用
     *
     * @param serialNo
     * @param isDisable
     */
    public void updateDisable(String serialNo, boolean isDisable) {
        if (!TextUtils.isEmpty(serialNo)) {
            ControllerBean oldController = mControllerBeanDao.queryBuilder()
                    .where(ControllerBeanDao.Properties.ControllerSerialNo.eq(serialNo))
                    .unique();
            if (oldController != null) {
                oldController.setIsDisable(isDisable);
                mControllerBeanDao.save(oldController);
            }
        }
    }

    /**
     * 通过serialNo获取控制器
     *
     * @param controllerSerialNo
     * @return
     */
    public ControllerBean getControllerBySerialNo(String controllerSerialNo) {
        return mControllerBeanDao.queryBuilder().where(ControllerBeanDao.Properties.ControllerSerialNo.eq(controllerSerialNo)).unique();
    }

    /**
     * 通过productModel获取控制器组
     *
     * @param productModel
     * @return
     */
    public List<ControllerBean> getControllerByProductModel(String productModel) {
        return mControllerBeanDao.queryBuilder().where(ControllerBeanDao.Properties.ProductModel.eq(productModel)).list();
    }

    /**
     * 通过productModel获取控制器组
     *
     * @param
     * @return
     */
    public List<ControllerBean> getAllControllerGroup() {
        List<ControllerBean> result = new ArrayList<>();
        List<ControllerBean> controllerBeans = mControllerBeanDao.queryBuilder().where(ControllerBeanDao.Properties.ProductModel.eq("0x0002")).list();
        for(int i = 0; i < controllerBeans.size();i++){
            ControllerBean controllerBean = controllerBeans.get(i);
            List<DeviceBean> deviceBeans = LLDeviceDBManager.getInstance(context).getDeviceByControllerSerialNoOnlyGroupDevice(controllerBean.getControllerSerialNo());
            controllerBean.setDeviceItems(deviceBeans);
            result.add(controllerBean);
        }
        return result;
    }

    /**
     * 删除设备
     *
     * @param controller
     */
    public void remove(ControllerBean controller) {
        if (controller == null)
            return;
        ControllerBean oldController = mControllerBeanDao.queryBuilder()
                .where(ControllerBeanDao.Properties.ControllerSerialNo.eq(controller.getControllerSerialNo()))
                .unique();
        if (oldController != null) {
            mControllerBeanDao.delete(oldController);
        }
    }

    /**
     * 删除设备
     *
     * @param serialNo
     */
    public void remove(String serialNo) {
        ControllerBean oldController = mControllerBeanDao.queryBuilder()
                .where(ControllerBeanDao.Properties.ControllerSerialNo.eq(serialNo))
                .unique();
        if (oldController != null) {
            mControllerBeanDao.delete(oldController);
        }
    }

    /**
     * 获得本地所有设备图片列表
     *
     * @return
     */
    public List<ControllerBean> getAll() {
        return mControllerBeanDao.queryBuilder()
                .orderAsc(ControllerBeanDao.Properties.ControllerSerialNo)
                .list();
    }

    /**
     * 获得本地所有场景图片列表
     *
     * @return
     */
    public List<ControllerBean> getHostControllers() {
        return mControllerBeanDao.queryBuilder()
                .where(ControllerBeanDao.Properties.IsSlave.eq(false))
                .orderAsc(ControllerBeanDao.Properties.ControllerSerialNo)
                .list();
    }

    public List<ControllerBean> getControllersByProductModel(String productModel) {
        return mControllerBeanDao.queryBuilder()
                .where(ControllerBeanDao.Properties.ProductModel.eq(productModel))
                .orderAsc(ControllerBeanDao.Properties.ControllerSerialNo)
                .list();
    }

    /**
     * 是否有主机设备
     *
     * @return
     */
    public boolean hasHostController() {
        long count =  mControllerBeanDao.queryBuilder()
                .where(ControllerBeanDao.Properties.IsSlave.eq(false))
                .count();
        return count > 0;
    }

    /**
     * 获取从机列表
     *
     * @return
     */
    public List<ControllerBean> getSlaveControllers(String masterSerialNo) {
        return mControllerBeanDao.queryBuilder()
                .where(ControllerBeanDao.Properties.IsSlave.eq(true), ControllerBeanDao.Properties.MasterSerialNo.eq(masterSerialNo))
                .orderAsc(ControllerBeanDao.Properties.Sort,ControllerBeanDao.Properties.ProductModel, ControllerBeanDao.Properties.Name)
                .list();
    }

    /**
     * 获得设备信息
     *
     * @return
     */
    public ControllerBean get(String serialNo) {
        return mControllerBeanDao.queryBuilder()
                .where(ControllerBeanDao.Properties.ControllerSerialNo.eq(serialNo))
                .unique();
    }
}
